<?php

function get_templates($type) {
    $templates = array();
    $template_dir = ROOT . 'www/themes/' . get_option('template');
    if (is_dir($template_dir)) {
        if ($dh = opendir($template_dir)) {
            while (($file = readdir($dh)) !== false) {
                if (strpos($file, '.') !== 0 && substr($file, -4) == '.php') {
                    if (is_file($template_dir . '/' . $file)) {
                        $template_data = get_template_data($template_dir . '/' . $file);
                        if (!empty($template_data['type']) && $template_data['type'] == $type && !empty($template_data['name'])) {
                            $template_data['tag'] = substr($file, 0, -4);
                            $templates[] = $template_data;
                        }
                    }
                }
            }
            closedir($dh);
        }
    }
    return $templates;
}

function get_templates_as_array($type) {
    $templates = get_templates($type);
    $results = array();
    foreach($templates as $template) {
        $results[$template['tag']] = $template['name'];
    }
    return $results;
}
function get_template_data($template_file ) {
    $template_data = implode( '', file( $template_file ));
    preg_match( '|Template type:(.*)$|mi', $template_data, $template_type );
    preg_match( '|Template name:(.*)$|mi', $template_data, $template_name );
    preg_match( '|Description:(.*)$|mi', $template_data, $description );
    $name = '';
    $type = '';
    if (isset($template_type[1])) {
        $type = trim($template_type[1]);
    }
    if (isset($template_name[1])) {
        $name = trim($template_name[1]);
    }
    return array('name' => $name, 'type' => $type);
}
